package com.health.mapp.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.health.db.model.EPayCashPayment;
import com.health.mapp.interImpl.PayActionServerImpl;
import com.health.mapp.utils.Constant;
import com.health.mapp.utils.MappMath;
import com.health.mapp.utils.PropertiesUtil;
import com.health.pay.alipay.AlipayNotify;
import com.sun.java_cup.internal.runtime.virtual_parse_stack;

/**
 *  * 注：日志未记
 * @author lenovo
 *
 */
public class AliPayNotifyService extends HttpServlet {

	private static Logger logger = Logger.getLogger(AliPayNotifyService.class);
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		logger.info("进入支付宝支付回调接口");
		Map<String, String> params = new HashMap<String, String>();
		Map requestParams = request.getParameterMap();

		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}

		logger.info("支付宝支付回调接口入参:");
		logger.info("----------params:");
		logger.info(params.toString());
		// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		// 商户订单号
		String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

		// 支付宝交易号
		String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

		// 交易状态
		String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");

		// 异步通知ID
		String notify_id = request.getParameter("notify_id");
		
		String total_amount=request.getParameter("total_amount");
		//request.getParameterMap()
		// sign
		String sign = request.getParameter("sign");

		if (notify_id != "" && notify_id != null) {
			if (AlipayNotify.verifyResponse(notify_id).equals("true"))// 判断成功之后使用getResponse方法判断是否是支付宝发来的异步通知。
			{
				if (AlipayNotify.getSignVeryfy(params, sign))// 使用支付宝公钥验签
				{
					logger.info("sign success");
					if (trade_status.equals("TRADE_FINISHED")
							|| trade_status.equals("TRADE_SUCCESS")) {
						

						EPayCashPayment payment = new EPayCashPayment();
						
						payment.setBankCashIdno(trade_no);
						payment.setPaycashTotal(new BigDecimal(total_amount)); 
						
						PayActionServerImpl impl = new PayActionServerImpl();
						impl.updatePayCashPaymentLog(out_trade_no, payment);
						
						try {
							impl.payAction(out_trade_no, Constant.CONSTANTS_PAYMENT_ALIPAY);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						logger.info("success");
						PrintWriter out = response.getWriter();
						out.println("success");
						out.flush();
						out.close();
					}
					

				} else// 验证签名失败
				{
					logger.info("sign fail");
					PrintWriter out = response.getWriter();
					out.println("sign fail");
					out.flush();
					out.close();
				}
			} else// 验证是否来自支付宝的通知失败
			{
				logger.info("response fail");
				PrintWriter out = response.getWriter();
				out.println("response fail");
				out.flush();
				out.close();
			}
		} else {
			logger.info("no notify message");
			PrintWriter out = response.getWriter();
			out.println("no notify message");
			out.flush();
			out.close();
		}

	}

}
